package com.example.com.daervideo.fragments;

import io.reactivex.Observable;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.com.daervideo.R;
import com.example.com.daervideo.activitys.users.DraftActivity;
import com.example.com.daervideo.databinding.FragmentUserRecycleviewBinding;
import com.example.com.daervideo.entity.BaseListEntity;
import com.example.com.daervideo.entity.BaseListEntity;
import com.example.com.daervideo.initerface.ApiService;
import com.example.com.daervideo.utils.RetrofitClient;
import com.example.com.daervideo.BR;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Created by i7-1 on 2018/12/3.
 */

public class TabContentFragment extends BaseFragment<FragmentUserRecycleviewBinding, BaseViewModel> {
    private List lists = new ArrayList();

    private int page = 1;
    private int pageSize = 10;
    private String type; //"发布", "打赏", "分享"
    private ApiService apiService;

    public static Fragment newInstance(String s) {
        TabContentFragment tabContentFragment = new TabContentFragment();
        Bundle bundle = new Bundle();
        bundle.putString("key", s);
        tabContentFragment.setArguments(bundle);
        return tabContentFragment;
    }


    @Override
    public int initContentView() {
        return R.layout.fragment_user_recycleview;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public BaseViewModel initViewModel() {
        return new BaseViewModel(context);
    }

    @Override
    public void initParam() {
        super.initParam();
        type = getArguments().getString("key");
    }

    @Override
    public void initData() {
        super.initData();
        apiService = RetrofitClient.getInstance().create(ApiService.class);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2);
        binding.uInclude.recyclerview.setLayoutManager(gridLayoutManager);
        binding.uInclude.recyclerview.setAdapter(new MyAdapter());
        binding.uInclude.refreshLayout.setFloatRefresh(true);
        ProgressLayout progressLayout = new ProgressLayout(context);
        binding.uInclude.refreshLayout.setHeaderView(progressLayout);
        binding.uInclude.refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                page++;
                getData();
            }

            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                page = 1;
                getData();
            }
        });
        binding.uInclude.refreshLayout.startRefresh();
    }

    private class MyAdapter extends RecyclerView.Adapter<RHolder> {

        @Override
        public RHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(context).inflate(R.layout.item_tab_img, parent, false);
            return new RHolder(inflate);
        }

        @Override
        public void onBindViewHolder(RHolder holder, final int position) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemClick(position);
                }
            });
        }

        @Override
        public int getItemCount() {
            return lists.size();
        }

    }


    public class RHolder extends RecyclerView.ViewHolder {
        public RHolder(View inflate) {
            super(inflate);
        }
    }

    private void getData() {
        Observable<BaseResponse<BaseListEntity>> observable;
        int userId = 0;
        if ("发布".equals(type)) {
            observable = apiService.mydeploy(userId, page, pageSize);
        } else if ("打赏".equals(type)) {
            observable = apiService.rewardList(userId, page, pageSize);
        } else {
            observable = apiService.rewardList(userId, page, pageSize);
        }

        observable.compose(RxUtils.bindToLifecycle(this)) //请求与View周期同步
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                    }
                })
                .subscribe(new Consumer<BaseResponse<BaseListEntity>>() {
                    @Override
                    public void accept(BaseResponse<BaseListEntity> response) throws Exception {
                        if (page == 1) {
                            binding.uInclude.refreshLayout.finishRefreshing();
                        } else {
                            binding.uInclude.refreshLayout.finishLoadmore();
                        }
                        if (response.getCode() == 0) {
                            binding.uInclude.setSize(response.getData().getPageItems().size());
                        } else {
                            ToastUtils.showShort(response.getMsg());
                        }
                    }
                }, new Consumer<ResponseThrowable>() {
                    @Override
                    public void accept(ResponseThrowable throwable) throws Exception {
                        if (page == 1) {
                            binding.uInclude.refreshLayout.finishRefreshing();
                        } else {
                            binding.uInclude.refreshLayout.finishLoadmore();
                        }
                        ToastUtils.showShort(throwable.message);
                        throwable.printStackTrace();
                    }
                });
    }

    private void itemClick(int position) {
        if ("发布".equals(type)) {
            Intent intent = new Intent(context, DraftActivity.class);
            startActivity(intent);
        } else if ("打赏".equals(type)) {

        } else {

        }

    }

}

